using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

/// <summary>
/// 物品拖拽管理器 - 处理物品的拖拽和放置功能
/// </summary>
public class ItemDragManager : MonoBehaviour
{
    [Header("拖拽设置")]
    public GameObject dragPreviewPrefab; // 拖拽预览预制体
    public float dragOffset = 0.5f; // 拖拽偏移量
    
    [Header("放置设置")]
    public LayerMask placementLayerMask = 1; // 放置层遮罩
    public float placementCheckRadius = 0.5f; // 放置检查半径
    
    // 私有变量
    private GameObject currentDragPreview; // 当前拖拽预览
    private GameObject draggedItem; // 正在拖拽的物品
    private Vector3 dragStartPosition; // 拖拽开始位置
    private bool isDragging = false; // 是否正在拖拽
    private PathHighlightManager highlightManager; // 高亮管理器引用
    
    // 缓存
    private Camera mainCamera;
    private Canvas uiCanvas;
    
    private void Awake()
    {
        mainCamera = Camera.main;
        uiCanvas = FindObjectOfType<Canvas>();
        
        // 获取高亮管理器
        highlightManager = FindObjectOfType<PathHighlightManager>();
    }
    
    private void Update()
    {
        if (isDragging)
        {
            UpdateDragPreview();
            CheckPlacementValidity();
        }
    }
    
    /// <summary>
    /// 开始拖拽物品
    /// </summary>
    /// <param name="item">要拖拽的物品</param>
    /// <param name="startPosition">开始位置</param>
    public void StartDragging(GameObject item, Vector3 startPosition)
    {
        if (isDragging) return;
        
        draggedItem = item;
        dragStartPosition = startPosition;
        isDragging = true;
        
        // 创建拖拽预览
        CreateDragPreview();
        
        // 通知高亮管理器开始拖拽
        if (highlightManager != null)
        {
            highlightManager.StartDragging(true);
        }
        
        // 禁用物品的碰撞器（避免干扰）
        SetItemCollidersEnabled(item, false);
    }
    
    /// <summary>
    /// 结束拖拽
    /// </summary>
    public void StopDragging()
    {
        if (!isDragging) return;
        
        // 检查是否可以放置
        bool canPlace = CheckCanPlace();
        
        if (canPlace)
        {
            PlaceItem();
        }
        else
        {
            ReturnItemToOriginalPosition();
        }
        
        // 清理拖拽状态
        CleanupDrag();
    }
    
    /// <summary>
    /// 创建拖拽预览
    /// </summary>
    private void CreateDragPreview()
    {
        if (dragPreviewPrefab == null) return;
        
        currentDragPreview = Instantiate(dragPreviewPrefab);
        
        // 设置预览的父对象为UI画布
        if (uiCanvas != null)
        {
            currentDragPreview.transform.SetParent(uiCanvas.transform, false);
        }
        
        // 复制物品外观到预览
        DragPreviewController previewController = currentDragPreview.GetComponent<DragPreviewController>();
        if (previewController != null && draggedItem != null)
        {
            previewController.CopyAppearanceFrom(draggedItem);
        }
        
        // 设置预览的初始位置
        UpdateDragPreview();
    }
    
    /// <summary>
    /// 更新拖拽预览位置
    /// </summary>
    private void UpdateDragPreview()
    {
        if (currentDragPreview == null) return;
        
        Vector3 mousePosition = Input.mousePosition;
        Vector3 worldPosition = mainCamera.ScreenToWorldPoint(mousePosition);
        worldPosition.z = 0;
        
        // 应用偏移
        worldPosition += Vector3.up * dragOffset;
        
        // 更新预览位置
        currentDragPreview.transform.position = worldPosition;
    }
    
    /// <summary>
    /// 检查放置有效性
    /// </summary>
    private void CheckPlacementValidity()
    {
        if (highlightManager == null) return;
        
        Vector3 mousePosition = Input.mousePosition;
        Vector3 worldPosition = mainCamera.ScreenToWorldPoint(mousePosition);
        worldPosition.z = 0;
        
        bool canPlace = highlightManager.CanPlaceItemAt(worldPosition);
        
        // 更新高亮状态
        highlightManager.UpdateDragState(canPlace);
        
        // 更新预览状态
        UpdatePreviewState(canPlace);
    }
    
    /// <summary>
    /// 更新预览状态
    /// </summary>
    private void UpdatePreviewState(bool canPlace)
    {
        if (currentDragPreview == null) return;
        
        DragPreviewController previewController = currentDragPreview.GetComponent<DragPreviewController>();
        if (previewController != null)
        {
            if (canPlace)
            {
                previewController.SetValidState();
            }
            else
            {
                previewController.SetInvalidState();
            }
        }
    }
    
    /// <summary>
    /// 检查是否可以放置
    /// </summary>
    private bool CheckCanPlace()
    {
        if (highlightManager == null) return false;
        
        Vector3 mousePosition = Input.mousePosition;
        Vector3 worldPosition = mainCamera.ScreenToWorldPoint(mousePosition);
        worldPosition.z = 0;
        
        return highlightManager.CanPlaceItemAt(worldPosition);
    }
    
    /// <summary>
    /// 放置物品
    /// </summary>
    private void PlaceItem()
    {
        if (draggedItem == null) return;
        
        Vector3 mousePosition = Input.mousePosition;
        Vector3 worldPosition = mainCamera.ScreenToWorldPoint(mousePosition);
        worldPosition.z = 0;
        
        // 获取格子中心位置
        Vector3Int cellPosition = highlightManager.GetCurrentHoveredCell();
        Vector3 placementPosition = highlightManager.GetCurrentHoveredWorldPosition();
        
        // 移动物品到放置位置
        draggedItem.transform.position = placementPosition;
        
        // 重新启用碰撞器
        SetItemCollidersEnabled(draggedItem, true);
        
        // 触发放置事件
        OnItemPlaced(draggedItem, placementPosition, cellPosition);
    }
    
    /// <summary>
    /// 将物品返回到原始位置
    /// </summary>
    private void ReturnItemToOriginalPosition()
    {
        if (draggedItem == null) return;
        
        draggedItem.transform.position = dragStartPosition;
        
        // 重新启用碰撞器
        SetItemCollidersEnabled(draggedItem, true);
        
        // 触发取消放置事件
        OnItemPlacementCancelled(draggedItem);
    }
    
    /// <summary>
    /// 清理拖拽状态
    /// </summary>
    private void CleanupDrag()
    {
        // 销毁拖拽预览
        if (currentDragPreview != null)
        {
            Destroy(currentDragPreview);
            currentDragPreview = null;
        }
        
        // 通知高亮管理器结束拖拽
        if (highlightManager != null)
        {
            highlightManager.StopDragging();
        }
        
        // 重置状态
        draggedItem = null;
        isDragging = false;
    }
    
    /// <summary>
    /// 设置物品碰撞器的启用状态
    /// </summary>
    private void SetItemCollidersEnabled(GameObject item, bool enabled)
    {
        if (item == null) return;
        
        Collider2D[] colliders = item.GetComponentsInChildren<Collider2D>();
        foreach (var collider in colliders)
        {
            collider.enabled = enabled;
        }
    }
    
    /// <summary>
    /// 物品放置成功事件
    /// </summary>
    private void OnItemPlaced(GameObject item, Vector3 position, Vector3Int cellPosition)
    {
        Debug.Log($"物品 {item.name} 已放置到位置 {position} (格子: {cellPosition})");
        
        // 这里可以添加更多放置逻辑
        // 例如：更新游戏状态、播放音效、触发动画等
    }
    
    /// <summary>
    /// 物品放置取消事件
    /// </summary>
    private void OnItemPlacementCancelled(GameObject item)
    {
        Debug.Log($"物品 {item.name} 放置已取消");
        
        // 这里可以添加更多取消逻辑
        // 例如：播放音效、显示提示等
    }
    
    /// <summary>
    /// 检查是否正在拖拽
    /// </summary>
    public bool IsDragging => isDragging;
    
    /// <summary>
    /// 获取当前拖拽的物品
    /// </summary>
    public GameObject CurrentDraggedItem => draggedItem;
    
    /// <summary>
    /// 获取当前拖拽预览
    /// </summary>
    public GameObject CurrentDragPreview => currentDragPreview;
}

/// <summary>
/// 可拖拽物品组件 - 添加到需要支持拖拽的物品上
/// </summary>
public class DraggableItem : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
    [Header("拖拽设置")]
    public bool canBeDragged = true; // 是否可以拖拽
    public bool returnToOriginalPosition = true; // 是否在取消时返回原位置
    
    private ItemDragManager dragManager;
    private Vector3 originalPosition;
    private bool isBeingDragged = false;
    
    private void Awake()
    {
        dragManager = FindObjectOfType<ItemDragManager>();
        originalPosition = transform.position;
    }
    
    public void OnBeginDrag(PointerEventData eventData)
    {
        if (!canBeDragged || dragManager == null) return;
        
        isBeingDragged = true;
        originalPosition = transform.position;
        
        // 通知拖拽管理器开始拖拽
        dragManager.StartDragging(gameObject, originalPosition);
    }
    
    public void OnDrag(PointerEventData eventData)
    {
        if (!isBeingDragged) return;
        
        // 拖拽逻辑由ItemDragManager处理
    }
    
    public void OnEndDrag(PointerEventData eventData)
    {
        if (!isBeingDragged || dragManager == null) return;
        
        isBeingDragged = false;
        
        // 通知拖拽管理器结束拖拽
        dragManager.StopDragging();
    }
    
    /// <summary>
    /// 设置是否可以拖拽
    /// </summary>
    public void SetDraggable(bool draggable)
    {
        canBeDragged = draggable;
    }
    
    /// <summary>
    /// 重置到原始位置
    /// </summary>
    public void ResetToOriginalPosition()
    {
        transform.position = originalPosition;
    }
} 